<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <!-- 警示语 -->
        <el-alert title="注意：只允许给第三分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>
      </el-row>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectedCatekeys"
            :options="catelist"
            :props="cateProps"
            @change="casHandleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="tabsHandleClick">
        <!-- 动态参数标签页 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isdisabled" @click="showAddDialog">添加参数</el-button>
          <el-table :data="manyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  class="tagInput"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性标签页 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isdisabled" @click="showAddDialog">添加属性</el-button>
          <el-table :data="onlyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i, scope.row)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  class="tagInput"
                ></el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeAddDialog"
    >
      <el-form :model="addForm" :rules="addFormRule" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeeditDialog"
    >
      <el-form :model="editForm" :rules="editFormRule" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品数据
      catelist: [],
      //   级联选择器中当前选中的商品id值
      selectedCatekeys: [],
      //   级联选择器的配置项
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   标签页默认选中项
      activeName: 'many',
      //   动态参数数据
      manyTableData: [],
      //   静态属性数据
      onlyTableData: [],
      //   添加对话框隐藏对话框
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRule: {
        attr_name: {
          required: 'true',
          message: '请输入参数名称',
          triggle: 'blur'
        }
      },
      // 编辑对话框
      editDialogVisible: false,
      editForm: {},
      // 验证规则
      editFormRule: {
        attr_name: {
          required: 'true',
          message: '请输入参数名称',
          triggle: 'blur'
        }
      }
    }
  },
  created() {
    this.getCatelist()
  },
  methods: {
    //   获取商品数据
    async getCatelist() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败！')
      }
      this.catelist = res.data
    },
    // 当级联选择器中选项变化时触发函数
    casHandleChange() {
      //   console.log(11)
      this.getParamsData()
    },
    // 标签页变化时触发函数
    tabsHandleClick() {
      console.log(this.activeName)
      this.getParamsData()
    },
    // 获取商品参数/属性
    async getParamsData() {
      if (this.selectedCatekeys.length !== 3) {
        this.selectedCatekeys = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败！')
      }
      res.data.forEach(item => {
        //   将字符串转为数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //  给添加独有的添加属性的隐藏或显示属性
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 显示对话框
    showAddDialog() {
      this.addDialogVisible = true
    },
    // 添加属性
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.$message.success('添加参数成功')
        this.getParamsData()
        this.addDialogVisible = false
      })
    },
    // 监听对话框，清除表单内容
    closeAddDialog() {
      this.$refs.addFormRef.resetFields()
    },
    // 编辑对话框
    async showEditDialog(attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 保存修改信息
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败！')
        }
        this.$message.success('修改参数成功！')
        this.getParamsData()
        this.showEditDialog = false
      })
      this.editDialogVisible = false
    },
    // 监听对话框，清除表单内容
    closeeditDialog() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除参数
    async delParams(attrId) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('用户取消删除！')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getParamsData()
    },
    // newTag 展示表单
    showInput(row) {
      row.inputVisible = true
      //   自动获取焦点
      //   $nextTick当页面重新加载后执行函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 处理添加
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //   如果没有return，则继续下面操作
      // 添加新属性到数组中，清空表单内容，隐藏表单
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求，保存标签
      this.saveTag(row)
    },
    //  标签删除
    handleClose(i, row) {
      // 根据索引删除元素
      row.attr_vals.splice(i, 1)
      this.saveTag(row)
    },
    //
    async saveTag(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('数据保存失败！')
      }
      this.$message.success('数据保存成功！')
    }
  },
  computed: {
    //   控制添加按钮禁用属性
    isdisabled() {
      if (this.selectedCatekeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取商品id值
    cateId() {
      if (this.selectedCatekeys.length === 3) {
        return this.selectedCatekeys[2]
      }
      return null
    },
    // 动态绑定添加对话框的标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-col {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.tagInput {
  width: 120px;
}
</style>
